<template>
  <div class="form-materials-bill-view">
    <el-table
      v-table-style
      v-loading="listLoading"
      :data="dataList"
      max-height="500"
      header-row-class-name="common-list-table-header__v2"
      border
      v-if="field.subFormFieldList && field.subFormFieldList.length > 0"
      row-key="MID"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        v-for="(column, index) in columns"
        :key="`${column.fieldName}_${index}`"
        :label="column.displayName"
        :prop="column.fieldName"
        :width="column.width"
        :min-width="column.minWidth || '150px'"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <!-- 数量 -->
          <template v-if="column.fieldName === 'num'">
            <template v-if="!scope.row.editable">
              <span>{{ scope.row[column.fieldName] }}</span>
              <i
                class="iconfont icon-edit-square"
                @click="editNum(scope.row, scope.$index)"
              ></i>
            </template>
            <template v-else>
              <input
                type="number"
                v-model="scope.row.num"
                :style="{ width: '80px' }"
                @change="changeNum(scope.row, scope.$index)"
                @blur="toggleNumEditable(scope.row, scope.$index)"
              />
            </template>
          </template>
          <template v-else-if="column.fieldName === 'sn'">
            <span class="link" @click="jumpMaterial(scope.row)">{{
              scope.row[column.fieldName]
            }}</span>
          </template>
          <template v-else>
            {{
              $formatFormField(column, scope.row)
            }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="120">
        <template slot-scope="scope">
          <el-dropdown class="dropdown" v-if="scope.row.level === 0">
            <span class="cur-point">
              {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
              <el-dropdown-item><div  @click="changeOrder(scope.row)">{{$t('product.btns.adjustPriority')}}</div></el-dropdown-item>
              <el-dropdown-item><div @click="handleClickDelete(scope.row)">{{$t('common.base.delete')}}</div></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="material-table-footer" v-if="totalItems">
      <p class="total-count">
        <i18n path="common.base.table.totalCount">
          <span place="count">{{ totalItems }}</span>
        </i18n>
      </p>
      <el-pagination
        class="table-pagination"
        background
        @current-change="handleCurrentChange"
        :page-size="paginationInfo.pageSize"
        :current-page="paginationInfo.pageNum"
        layout="prev, pager, next"
        :total="totalItems"
      >
      </el-pagination>
    </div>

    <OrderMaterial ref="orderMaterial" @save="saveOrder" />
  </div>
</template>

<script>
import { MessageBox } from 'element-ui';
import Platform from '@src/util/platform.ts';
import {
  getProductTypeMaterielBill,
  deleteMateriel,
  relationMateriel,
  sortMaterial,
} from '@src/api/ProductV2Api';

/** util */
import MathUtil from '@src/util/math';

import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';

import OrderMaterial from './OrderMaterial.vue';

export default {
  name: 'form-materials-bill-view',
  props: {
    field: {
      type: Object,
      default: () => ({}),
    },
    catalogId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      dataList: [],
      totalItems: 0,
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
      },
      listLoading: false,
    };
  },
  computed: {
    columns() {
      let tableColumns = [
        {
          displayName: this.$t('common.fields.orderNo.displayName'),
          fieldName: 'customIndex',
          setting: {
            originalFormType: 'text',
          },
        },
        ...(this.field?.subFormFieldList || []),
        {
          displayName: this.$t('product.materialFields.num.displayName'),
          fieldName: 'num',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          fieldName: 'createUserName',
          displayName: this.$t('common.base.createUser'),
          formType: 'user',
          setting: {
            originalFormType: 'user',
          },
        },
        {
          fieldName: 'createTime',
          displayName: this.$t('common.base.column.createTime'),
          formType: 'datetime',
          setting: {
            originalFormType: 'datetime',
          },
        },
      ];
      return tableColumns;
    },
  },
  mounted() {
    this.fetchMaterialList();
  },
  methods: {
    changeOrder(row) {
      this.$refs.orderMaterial.open(row)
    },
    saveOrder({ row, number }) {
      if (number > this.totalItems) {
        number = this.totalItems;
      }
      sortMaterial({
        id: row.relationId,
        oldSortId: row.sortId,
        newSortId: number
      }).then(res => {
        if(res.code !== 0) {
          return Platform.toast(res.message, 'error');
        }
        this.fetchMaterialList();
      }).catch(err => {
        console.error(err);
      });
    },
    // 获取物料清单
    async fetchMaterialList() {
      this.listLoading = true;
      try {
        let res = await getProductTypeMaterielBill({
          catalogId: this.catalogId,
          ...this.paginationInfo,
        });

        if (!res.success) return Platform.toast(res.message, 'error');

        let { list = [], total = 0 } = res.result;

        this.dataList = (list || []).map(item => {
          return {
            ...item,
            level: 0,
            editable: false,
          };
        });
        this.setIndex(this.dataList);
        this.totalItems = total;
        this.listLoading = false;
      } catch (error) {
        console.warn('获取物料清单fetchMaterialList', error);
      }
    },
    setIndex(trees, parentIndex = '') {
      if(!trees) return;
      trees.forEach((tree, index) => {
        tree.customIndex = `${parentIndex}${++index}`;
        tree.currentSort = index++;
        // 唯一标识
        tree.MID = `${tree.id}_${tree.customIndex}`;
        if(tree.children && tree.children.length > 0) {
          this.setIndex(tree.children, `${tree.customIndex}.`);
        }
      });
    },
    // 点击删除
    handleClickDelete(row) {
      let materielList = [
        {
          materielId: row.id,
          materielName: row.name,
        },
      ];

      MessageBox.confirm(
        this.$t('product.productType.tips.tip32'),
        this.$t('common.base.toast'),
        {
          confirmButtonText: this.$t('common.base.makeSure'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              deleteMateriel({
                catalogId: this.catalogId,
                materielList,
              }).then(res => {
                instance.confirmButtonLoading = false;
                if (!res.success) {
                  return Platform.toast(res.message, 'error');
                }

                Platform.toast(this.$t('common.base.tip.deleteSuccess'), 'success');
                done();
                this.paginationInfo.pageNum = 1;
                this.fetchMaterialList();
                this.$emit('handleDelete');
              });
            } else {
              done();
            }
          },
        }
      );
    },
    // 切换分页
    handleCurrentChange(pN) {
      this.paginationInfo.pageNum = pN;
      this.fetchMaterialList();
    },
    /**
     * @description 数量小数位
     */
    decimalNumber(num) {
      let count = MathUtil.decimalNumber(num);
      if (count != 0) return 0;
    },
    // 编辑数量
    editNum(row, index) {
      row.backupNum = row.num;
      this.toggleNumEditable(row, index);
    },
    // 修改数量
    changeNum(item, index) {
      let value = Number(item.num);
      let count = this.decimalNumber(value);
      if (value <= 0 || count == 0) {
        Platform.alert(this.$t('product.tips.inputLimitTip', {num: '0'}));
        // 编辑错了恢复数据
        item.num = item.backupNum;
        return;
      }
      this.editMaterialNum(item);
    },
    toggleNumEditable(row, index) {
      row.editable = !row.editable;
      this.$set(this.dataList, index, row);
    },
    // 编辑物料数量
    editMaterialNum(val) {
      let materielList = [
        {
          materielId: val.id,
          materielName: val.name,
          materielNum: Number(val.num),
        },
      ];

      relationMateriel({
        catalogId: this.catalogId,
        materielList,
      }).then(res => {
        if (!res.success) {
          return this.$notify.error({
            message: res.message,
            duration: 2000,
          });
        }
        this.fetchMaterialList();
      });
    },
    // 跳转到物料 TODO
    jumpMaterial({ id, sn }) {
      openAccurateTab({
        type: PageRoutesTypeEnum.PageItemsDetail,
        key: sn,
        titleKey: `-${sn}`,
        params: `id=${id}`,
      });
    },
  },
  components: {
    OrderMaterial,
  }
};
</script>
<style lang="scss" scoped>
.form-materials-bill-view {
  ::v-deep .el-table {
    border: 1px solid #e8e8e8;
  }
  .link {
    cursor: pointer;
    color: $color-primary-light-6;
    &:hover {
      text-decoration: underline;
    }
  }
  .material-table-footer {
    display: flex;
    justify-content: space-between;

    .total-count {
      padding: 0 10px;
      font-size: 12px;
      margin: 0;
      line-height: 46px;
      span {
        padding: 0 5px;
        @include fontColor();
      }
    }
    .table-pagination {
      text-align: right;
      margin-top: 7px;
    }
  }
  .cur-point {
    color: $color-primary-light-6;
  }
}
.lang-select-dropdown {
  margin-top: 0!important;
}
</style>

